package com.yd.cfckc.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cuiyufeng
 * @email cuiyufeng1458@yundasys.com
 * @date 2020/10/16 3:43 下午
 */
public class StringUtils {

    /**
     *  将 s 进行 BASE64 编码
     */
    public static String getBASE64(String s,String charEncode)throws Exception  {
        if (s == null)
            return null;
        BASE64Encoder decoder = new BASE64Encoder();
//		System.out.println("-----"+ decoder.encodeBuffer(s.getBytes(charEncode))  );
//
//		System.out.println("----->>" + decoder.encode(s.getBytes(charEncode))  );

        return decoder.encodeBuffer(s.getBytes(charEncode)) ;
    }

    public static String getBASE64(String s)throws Exception  {
        return getBASE64(s, "UTF-8");
    }
    /**
     * 将 BASE64 编码的字符串 s 进行解码
     */
    public static String getFromBASE64(String s,String charEncode) throws Exception {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b,charEncode);
        } catch (Exception e) {
            throw e;
        }
    }
    //判断是否含有中文字符
    public static boolean hasCHchar(String str){
        return !(str.getBytes().length == str.length());
    }
    //字符串是否为空
    public static boolean isEmpty(String str){
        if (str != null && str.length() > 0) {
            return false;
        }
        return true;
    }
    //是否为纯汉字的字符串
    public static boolean hasAllCHchar(String str){
        return (str.getBytes().length == (2*str.length()));
    }

    /**
     * 获取字符串字节长度 汉字算两个长度
     * @param str
     * @return
     * @author xuesheng
     */
    public static int charLength(String str){
        if(null == str){
            return 0;
        }
        return str.getBytes().length;
    }
    /**
     * 字符串截取 如果是汉字汉字算两个长度 不会出现汉字不能截取的问题
     * @param str 字符串
     * @param len 截取长度
     * @return
     * @author xuesheng
     */
    public static String getLimitLengthString(String str, int len) {
        try {
            int counterOfDoubleByte = 0;
            byte[] b = str.getBytes();
            if (b.length <= len)
                return str;
            for (int i = 0; i < len; i++) {
                if (b[i] < 0) {
                    counterOfDoubleByte++;
                }
            }
            if (counterOfDoubleByte % 2 == 0)
                return new String(b, 0, len);
            else
                return new String(b, 0, len - 1);
        } catch (Exception ex) {
            return "";
        }
    }

    /**
     *
     * @method:字符串替换
     * @description:
     * @param strSource
     *            原字符串
     * @param strFrom
     *            被替换的
     * @param strTo
     *            替换为
     * @return 替换后的字符串
     */
    public static String replace(String strSource, String strFrom, String strTo) {
        if (strSource == null)
            return null;
        if (strFrom == null || strFrom.equals("")) {
            return strSource;
        }
        StringBuffer strDest = new StringBuffer("");
        int intFromLen = strFrom.length();
        int intPos;

        while ((intPos = strSource.indexOf(strFrom)) != -1) {
            strDest.append(strSource.substring(0, intPos));
            strDest.append(strTo);
            strSource = strSource.substring(intPos + intFromLen);
        }
        strDest.append(strSource);

        return strDest.toString();
    }
    /**
     *
     * @method:过滤json特殊字符串，做字符串转义
     * @description:替换中会吧 '替换为\' "替换为\"
     * @param strSource
     * @return
     * @author 张雪生
     */
    public static String htlmSpecialCharConvert(String strSource) {
        String result = replace(strSource, "'", "\\\'");
        result = replace(result, "\"", "\\\"");
        result = replaceBlank(result);
        return result;
    }
    /**
     *
     * @method:去掉字符串中的回车符号
     * @description:
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\r|\n");
            Matcher m = p.matcher(str);
            //dest = m.replaceAll("<br/>");
            dest = m.replaceAll("；");
        }
        return dest;
    }
    /**
     *
     * @method:用指定的字符替换字符串中的回车符号
     * @description:
     * @param str 源字符串
     * @param tar 被替换的字符串
     * @return
     * @author 张雪生
     */
    public static String replaceBlank(String str,String tar) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\r|\n");
            Matcher m = p.matcher(str);
            //dest = m.replaceAll("<br/>");
            dest = m.replaceAll(tar);
        }
        return dest;
    }
    /**
     *
     * @method:取得字符串的长度
     * @description:
     * @param strSource
     * @return
     * @author 张雪生
     */
    public static int lenth(String strSource) {
        return strSource.length();
    }
    /**
     *
     * @method:字符串分割 数组
     * @description:
     * @param source
     * @param delim
     * @return
     * @author 张雪生
     */
    public static String[] split(String source, String delim) {
        String[] wordLists;
        if (source == null) {
            wordLists = new String[1];
            return wordLists;
        }
        if (delim == null) {
            delim = ",";
        }
        StringTokenizer st = new StringTokenizer(source, delim);
        int total = st.countTokens();
        wordLists = new String[total];
        for (int i = 0; i < total; i++) {
            wordLists[i] = st.nextToken();
        }
        return wordLists;
    }
    /**
     *
     * @method: z字符串截取，
     * @description:
     * @param source
     * @param length
     * @return 从开始起截取的子串
     * @author 张雪生
     */
    public static String substring(String source, int length) {
        String temp;
        if (source == null || source.equals("")) {
            return "";
        }
        if (source.length() > length) {
            temp = source.substring(0, length);
        } else {
            temp = source;
        }
        return temp;
    }
    /**
     *
     * @method: a按照某个字符分割
     * @description:
     * @param source
     * @param delim
     * @return
     * @author 张雪生
     */
    public static String[] split(String source, char delim) {
        return split(source, String.valueOf(delim));
    }
    /**
     *
     * @method:按照“,”分割字符串为数组
     * @description:
     * @param source
     * @return
     * @author 张雪生
     */
    public static String[] split(String source) {
        return split(source, ",");
    }
    /**
     *
     * @method: 数据字符串拼接
     * @description:
     * @param array 数组
     * @param delim 拼接符合
     * @return
     * @author 张雪生
     */
    public static String combineStringArray(String[] array, String delim) {
        if (array == null) {
            return "";
        }
        int length = array.length - 1;
        if (delim == null) {
            delim = "";
        }
        StringBuffer result = new StringBuffer(length * 8);
        for (int i = 0; i < length; i++) {
            result.append(parseNull(array[i], ""));
            result.append(delim);
        }
        result.append(parseNull(array[length], ""));
        return result.toString();
    }
    /**
     *
     * @method: 去左空格
     * @description:
     * @param value
     * @return
     * @author 张雪生
     */
    public static String trimLeft(String value) {
        String result = value;
        if (result == null)
            return result;
        char ch[] = result.toCharArray();
        int index = -1;
        for (int i = 0; i < ch.length; i++) {
            if (Character.isWhitespace(ch[i])) {
                index = i;
            } else {
                break;
            }
        }
        if (index != -1) {
            result = result.substring(index + 1);
        }
        return result;
    }
    /**
     *
     * @method:去右空格
     * @description:
     * @param value
     * @return
     * @author 张雪生
     */
    public static String trimRight(String value) {
        String result = value;
        if (result == null)
            return result;
        char ch[] = result.toCharArray();
        int endIndex = -1;
        for (int i = ch.length - 1; i > -1; i--) {
            if (Character.isWhitespace(ch[i])) {
                endIndex = i;
            } else {
                break;
            }
        }
        if (endIndex != -1) {
            result = result.substring(0, endIndex);
        }
        return result;
    }
    /**
     *
     * @method:将字符串中的某些字符替换为指定字符
     * @description:
     * @param source 原字符串
     * @param escapeCharMap 将被替换 字符集合 key为要替换的字符 value为替换为的字符串
     * @return
     * @author 张雪生
     */
    public static String escapeCharacter(String source, Map escapeCharMap) {
        if (source == null || source.length() == 0) {
            return source;
        }
        if (escapeCharMap.size() == 0) {
            return source;
        }
        StringBuffer sb = new StringBuffer();
        StringCharacterIterator sci = new StringCharacterIterator(source);
        for (char c = sci.first(); c != StringCharacterIterator.DONE; c = sci
                .next()) {
            String character = String.valueOf(c);
            if (escapeCharMap.containsKey(character)) {
                character = (String) escapeCharMap.get(character);
            }
            sb.append(character);
        }
        return sb.toString();
    }
    /**
     *
     * @method:将字符串中的某些字符串替换为指定字符
     * @description:
     * @param source 原字符串
     * @param escapeCharMap 将被替换 字符集合 key为要替换的字符窜 value为替换为的字符串
     * @return
     * @author 张雪生
     */
    public static String escapeString(String source, Map escapeStringMap) {
        if (source == null || source.length() == 0) {
            return source;
        }
        if (escapeStringMap.size() == 0) {
            return source;
        }
        java.util.Collection colValues = escapeStringMap.values();
        java.util.Collection colKeys = escapeStringMap.keySet();
        Iterator itValues = colValues.iterator();
        Iterator itKeys = colKeys.iterator();
        while (itValues.hasNext() && itKeys.hasNext()) {
            source = replace(source, (String) (itKeys.next()),
                    (String) (itValues.next()));
        }
        return source;
    }
    /**
     *
     * @method:字符串转码 将Gb2312转为 ISO8859-1
     * @description:
     * @param str
     * @return
     * @author 张雪生
     */
    public static String parseGBtoISO(String str) {
        String ss = str;
        if (ss != null) {
            try {
                ss = new String(ss.getBytes("GB2312"), "ISO8859-1");
            } catch (UnsupportedEncodingException ex) {
                return str;
            }
            return ss;
        } else {
            return null;
        }
    }
    /**
     *
     * @method:将iso转换为 GBK
     * @description:
     * @param str
     * @return
     * @author 张雪生
     */
    public static String parseISOtoGB(String str) {
        if (str == null)
            return "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) <= '\377')
                continue;
            return str;
        }
        try {
            return new String(str.getBytes("ISO8859-1"), "GBK");
        } catch (UnsupportedEncodingException ex) {
            return str;
        }
    }
    /**
     *
     * @method:ISO转换为 UTF-8
     * @description:
     * @param str
     * @return
     * @author 张雪生
     */
    public static String parseISOtoUTF(String str) {
        if (str == null)
            return "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) <= '\377')
                continue;
            return str;
        }
        try {
            return new String(str.getBytes("ISO8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            return str;
        }
    }
    /**
     *
     * @method:字符串数组中是否包含 某个字符
     * @description:
     * @param strings 字符串数组
     * @param string  字符串
     * @param caseSensitive 是否区分大小写
     * @return
     * @author 张雪生
     */
    public static boolean contains(String[] strings, String string,
                                   boolean caseSensitive) {
        for (int i = 0; i < strings.length; i++) {
            String string1 = strings[i];
            if (caseSensitive) {
                if (string1.equals(string)) {
                    return true;
                }
            } else {
                if (string1.equalsIgnoreCase(string)) {
                    return true;
                }
            }
        }
        return false;
    }
    /***
     *
     * @method:字符串中总是否包某个字符串 区分大小写
     * @description:
     * @param strings
     * @param string
     * @return
     * @author 张雪生
     */
    public static boolean contains(String[] strings, String string) {
        return contains(strings, string, true);
    }
    /***
     *
     * @method:字符串中总是否包某个字符串 不区分大小写
     * @description:
     * @param strings
     * @param string
     * @return
     * @author 张雪生
     */
    public static boolean containsIgnoreCase(String[] strings, String string) {
        return contains(strings, string, false);
    }

    public static String parseNull(Object s, String rtnstr) {
        return parseNull(s, "", rtnstr);
    }

    public static String parseNull(Object object, String format, String rtnstr) {
        SimpleDateFormat dateFormat;
        if (rtnstr == null)
            rtnstr = "";
        if (object == null) {
            return rtnstr;
        } else if (object instanceof String) {
            if (object.toString().length() == 0) {
                return rtnstr;
            } else {
                return object.toString();
            }
        } else if (object instanceof Date) {
            if (format == null || format.length() == 0)
                format = "yyyy-MM-dd";
            dateFormat = new SimpleDateFormat(format);
            return dateFormat.format((Date) object);
        } else {
            return object.toString();
        }
    }
    /**
     *
     * @method:获取UUID
     * @description:
     * @return
     * @author 张雪生
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 方法说明:空字符串
     * @param tstrr
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2008-11-30
     * @author liman
     */
    public static String isJavaNull(String tstrr) {
        try {
            if (tstrr == null || "null".equals(tstrr.trim())) {
                return "";
            } else {
                return tstrr.trim();
            }
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 方法说明:对象判断是否为空
     * @param tstrr
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2008-11-30
     * @author liman
     */
    public static String isJavaNull(Object tstrr) {
        if (tstrr == null) {
            return "";
        }

        String tstrr_temp = String.valueOf(tstrr);
        if ("null".equals(tstrr_temp.trim())) {
            return tstrr_temp.trim();
        } else {
            return tstrr_temp;
        }
    }

    /**
     * 方法说明:字符为空替换为html 空格
     * @param str
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2008-11-30
     * @author liman
     */
    public static String isHtmlNull(String str) {

        if (str == null || "".equals(str.trim()) || "null".equals(str.trim())) {
            return "&nbsp";
        } else {
            return str.trim();
        }
    }

    /**
     * 方法说明:数字字符转换为数字
     * @param str
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2008-11-30
     * @author liman
     */
    /**
     * String类型转int
     * @param str
     * @return
     */
    public static int string2int(String str) {
        try {

            //System.out.println("版本号："+str);
            if (str == null || "".equals(str)) {
                return 0;
            } else {
                return Integer.valueOf(str);
            }
        } catch (Exception e) {
            return 0;
        }

    }

    /**
     * 方法说明:
     * @param str
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2008-11-30
     * @author liman
     */
    /**
     * String类型转int
     * @param str
     * @return
     */
    public static int string2int(Object obj) {
        try {

            //System.out.println("版本号："+str);
            if (obj == null) {
                return 0;
            } else {
                return Integer.valueOf(isJavaNull(obj));
            }
        } catch (Exception e) {
            return 0;
        }

    }


    /**
     * 方法说明:
     * @param str
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2008-11-30
     * @author liman
     */
    /**
     * String类型转int
     * @param str
     * @return
     */
    public static double string2Double(Object obj) {
        try {

            if (obj == null || "".equals(isJavaNull(obj))) {
                return 0.0;
            } else {
                return Double.valueOf(isJavaNull(obj));
            }
        } catch (Exception e) {
            throw new NumberFormatException();
        }

    }

    /**
     * 替换空格
     * @param str
     * @return
     */
    public static String getStringNoBlank(String str) {
        if (str != null && !"".equals(str)) {
            StringBuffer noblankstr = new StringBuffer("");
            Pattern p = Pattern.compile("\\s|\t|\r|\n");
            Matcher m = p.matcher(str);
            String strNoBlank = m.replaceAll(",");

            //System.out.println("---------" + strNoBlank + "-----------");

            String[] temp = strNoBlank.split(",");
            for (int i = 0; i < temp.length; i++) {
                if ("".equals(temp[i])) {

                } else if (i == temp.length - 1) {
                    noblankstr.append(temp[i]);
                } else {
                    noblankstr.append(temp[i]).append(",");
                }
            }

            return noblankstr.toString();
        } else {
            return null;
        }
    }


    private static String replaceString(String strData, String regex,
                                        String replacement) {
        if (strData == null)
            return null;

        int index = strData.indexOf(regex);
        String strNew = "";
        if (index >= 0) {
            while (index >= 0) {
                strNew += strData.substring(0, index) + replacement;
                strData = strData.substring(index + regex.length());
                index = strData.indexOf(regex);
            }
            strNew += strData;
            return strNew;
        }
        return strData;
    }

    /**
     * 转义处理
     *
     * @param strData
     * @return
     */
    public static String encodeString(String strData) {
        if (strData == null)
            return "";

        strData = replaceString(strData, "&", "&amp;");
        strData = replaceString(strData, "<", "&lt;");
        strData = replaceString(strData, ">", "&gt;");
        strData = replaceString(strData, "'", "&apos;");
        strData = replaceString(strData, "\"", "&quot;");
        return strData;
    }
    /**
     *
     * @method:转义特殊字符
     * @description:
     * @param strData
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: Aug 2, 20122:30:12 PM
     * @author 张雪生
     * @version 1.0
     * @since:
     */
    public static String decodeString(String strData) {
        strData = replaceString(strData, "&amp;", "&");
        strData = replaceString(strData, "&lt;", "<");
        strData = replaceString(strData, "&gt;", ">");
        strData = replaceString(strData, "&apos;", "'");
        strData = replaceString(strData, "&quot;", "\"");

        return strData;
    }



    /**
     *
     * @method:返回plainText的MD5摘要
     * @description:
     * @param plainText
     * @return
     * @throws NoSuchAlgorithmException
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2012-11-5下午6:43:19
     * @author 路来军
     * @version 1.0
     * @since:
     */
    public static String MD5Encode(String plainText) throws NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(plainText.getBytes());
        byte b[] = md.digest();
        int i;
        StringBuffer buf = new StringBuffer();
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        return buf.toString();

    }

    /**
     *
     * @method: 由传入的两个参数加入一个无意义的特定字符串合成一个确认码
     * @description:
     * @param param1
     * @param param2
     * @return
     * <B>修改记录:</B><BR>
     * <PRE>
     * 日期     修改者   修改内容
     * <PRE>
     * Date: 2012-11-5下午6:48:18
     * @author Lewis
     * @version 1.0
     * @throws NoSuchAlgorithmException
     * @since:
     */
    public static String makeVerifyCode(String param1, String param2) throws NoSuchAlgorithmException {

        return MD5Encode(param1+ MD5Encode(param2)+"sac4dhc6omqdgzbctem34s80rizb7qmx");

    }
    /**
     * 格式化字符串不为null
     * @param str
     * @return
     */
    public static String formatStrNotNull(String str) {
        if (str == null || str.equals("null")) {
            return "";
        }
        return str.trim();
    }
    /**
     *
     * 过滤关键字符，返回TRUE则表示通过。
     *
     * @param str
     *            源字符串
     * @param minLen
     *            最小长度，不写即不验证
     * @param maxLen
     *            最大长度，不写即不验证
     * @return
     * @since 3.0_2013-1-11
     */
    public static boolean regexString(String str, Integer minLen, Integer maxLen) {
        formatStrNotNull(str);
        if ((null != minLen && null != maxLen) && (str.length() < minLen || str.length() > maxLen)) {
            return false;
        }
        // 正则过滤特殊字符
        Pattern regexp = Pattern.compile("[^<>&\\r\\n\\t'\"]*");
        return regexp.matcher(str).matches();
    }
}
